package thread;

import org.omg.PortableServer.THREAD_POLICY_ID;

import java.util.concurrent.locks.ReentrantLock;

public class SellTicket {
    public static void main(String[] args) {
        Window w = new Window();
        Thread a = new Thread(w);
        Thread b = new Thread(w);
        Thread c = new Thread(w);
        a.start();
        b.start();
        c.start();
    }

}

class Window implements Runnable {
    private int tickets = 100;
    Object o = new Object();
    ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        sell3();
    }



    private void sell3() {
        while (true) {
            lock.lock();
            if (tickets > 0) {
                System.out.println(Thread.currentThread().getName() + "----" + tickets);
                tickets--;
            }
            lock.unlock();
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private void sell2() {
        while (true) {
            synchronized (o) {
                if (tickets > 0) {
                    System.out.println(Thread.currentThread().getName() + "----" + tickets);
                    tickets--;
                }
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    private void sell1() {
        while(true){
            sell();
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public synchronized void sell() {
        if (tickets > 0) {
            System.out.println(Thread.currentThread().getName() + "----" + tickets);
            tickets--;
        }
    }
}
